<?php


namespace app\home\controller;


use app\base\BaseController;
use app\finance\model\Expense as ExpenseList;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class SaleContract extends BaseController
{
    protected $title='销售合同';
    protected $table='sale_contract';
    protected $scType=1;
    protected $checkType=25;
    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['qo.status','>',-1];
            $where[]=['qo.type','=',$this->scType];

            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['qo.status','=',$this->param['status']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['py.name','like','%'.$this->param['name'].'%'];
            }
            if (isset($this->param['salUnit'])&&$this->param['salUnit']){
                $where[]=['d.title','like','%'.$this->param['salUnit'].'%'];
            }
            if (isset($this->param['orderNum'])&&$this->param['orderNum']){
                $where[]=['qo.orderNum','like','%'.$this->param['orderNum'].'%'];
            }
            if (isset($this->param['orderDate'])&&$this->param['orderDate']){
                $dates=explode('~',$this->param['orderDate']);
                $where[]=['qo.orderDate','between',$dates];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->alias('qo')
                ->leftJoin('purveyor py','py.id=qo.punterId')
                ->leftJoin('department d','d.id=qo.salesUnitId')
                ->leftJoin('print_template pt','pt.id=qo.printTemplate')
                ->where($where)
                ->field('qo.*,py.name as pName,d.title as dName,pt.name as printTemplateName')
                ->order('qo.id DESC')
                ->paginate($rows)->each(function ($item){
               $savedMoney=Db::name('money_order_contract_detail')->where('type',1)
                    ->where('status',2)->where('contractOrder',$item['orderNum'])->sum('money');
                    $item['savedMoney']=$savedMoney?$savedMoney:0;
                    if ($item['countMoney']!=0){
                        $item['savedProp']=round(($savedMoney/$item['countMoney'])*100);
                    }else{
                        $item['savedProp']=0;
                    }

                    $item['invoiceMoney']=Db::name('invoice')->where('check_status',5)->where('contract_id',$item['id'])->sum('amount');
                    $item['refundMoney']=Db::name('money_order')->where('type',2)
                        ->where('status',2)->where('contractOrder',$item['orderNum'])->sum('money');
                    $saleUsers=Db::name('admin')->where('id','in',$item['saleId'])->column('name');
                    $item['saleName']=implode(',',$saleUsers);
                    return $item;
                });
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
//            halt($param);
            $mx=$param['mx']??[];
            unset($param['mx']);
            if (!$mx){
                return to_assign(1,'请添加明细');
            }
            if (!$param['punterId']||!$param['salesUnitId']
                ||!$param['saleId']){
                return to_assign(1,'参数有误');
            }
            $mxId=$mx['mxid']??[];
            $mdId=$mx['mdId']??[];
            $bjNum=$mx['bjNum']??[];
            $bjPrice=$mx['bjPrice']??[];
//            $mdPrice=$mx['mdPrice']??[];
            $discount=$mx['discount']??[];
            $taxMoney=$mx['taxMoney']??[];
            $noTaxPrice=$mx['noTaxPrice']??[];
            $noTaxMoney=$mx['noTaxMoney']??[];
            $bjMoney=$mx['bjMoney']??[];
            $bjTime=$mx['bjTime']??[];
            $remark=$mx['remark']??[];
            $khlh=$mx['khlh']??[];
            $proCode=$mx['proCode']??[];
            $quotationOderNum=$mx['quotationOderNum']??[];
            $quotationDetailId=$mx['quotationDetailId']??[];
//            $timeLong=$mx['timeLong']??[];
            $param['update_time']=time();
            $countMoney=0;
            foreach ($bjMoney as $v){
                $countMoney+=$v;
            }
            $param['countMoney']=$countMoney;
            $id=$this->param['id']??0;

            $flow_list = Db::name('Flow')->where('id',$param['flow_id'])->value('flow_list');
            $flow = unserialize($flow_list);
            $haseFolow=Db::name('FlowStep')->where(['action_id'=>$param['id'],'type'=>4,'delete_time'=>0])->find();
            Db::startTrans();
            try {

                if ($id > 0&&$haseFolow) {
                    $param['status']=3;
                    $param['check_status']=1;
                    Db::name($this->table)->strict(false)->field(true)->update($param);

//                    Db::name('FlowStep')->where(['action_id'=>$param['id'],'type'=>4,'delete_time'=>0])->update(['delete_time'=>time()]);
//                    Db::name('FlowRecord')->where(['action_id'=>$param['id'],'type'=>4,'delete_time'=>0])->update(['delete_time'=>time()]);
                    if (!isset($param['check_admin_ids'])) {
                        if($flow[0]['flow_type'] == 1){
                            //部门负责人
                            $leader = get_department_leader($this->uid);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else if($flow[0]['flow_type'] == 2){
                            //上级部门负责人
                            $leader = get_department_leader($this->uid,1);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else{
                            $param['check_admin_ids'] = $flow[0]['flow_uids'];
                        }
                        foreach ($flow as $key => &$value){
                            $value['action_id'] = $param['id'];
                            $value['sort'] = $key;
                            $value['type'] = 4;
                            $value['create_time'] = time();
                        }
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
                    }
                    else{
                        $flow_step = array(
                            'action_id' => $param['id'],
                            'type' => 4,
                            'flow_uids' => $param['check_admin_ids'],
                            'create_time' => time()
                        );
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->where('id',$haseFolow['id'])->update($flow_step);
                    }
//添加提交申请记录
                    $checkData=array(
                        'action_id' => $id,
                        'check_user_id' => $this->uid,
                        'content' => '重新提交申请',
                        'type' => 4,
                        'check_time' => time(),
                        'create_time' => time()
                    );
                     Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);

                    add_log('edit', $param['id'], $param,$this->title);
                    //发送消息通知
                    $msg=[
                        'from_uid'=>$this->uid,
                        'title'=>'合同审批',
                        'action_id'=>$id
                    ];
                    $users = $param['check_admin_ids'];
                    sendMessage($users,51,$msg,$this->table);

                } else {
                    $param['createId']=$this->uid;
                    $param['type']=$this->scType;
                    $param['departId']=$this->did;
                    $param['create_time'] = time();
                    $param['check_status']=1;
                    $param['status']=3;
                    if ($id){
                        unset($param['createId']);
                        unset($param['departId']);
                        unset($param['create_time']);
                       Db::name($this->table)->strict(false)->field(true)->update($param);
                    }else{
                        $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    }

                    if (!isset($param['check_admin_ids'])) {
                        if($flow[0]['flow_type'] == 1){
                            //部门负责人
                            $leader = get_department_leader($this->uid);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else if($flow[0]['flow_type'] == 2){
                            //上级部门负责人
                            $leader = get_department_leader($this->uid,1);
                            if($leader == 0){
                                return to_assign(1,'审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                            }
                            else{
                                $param['check_admin_ids'] = $leader;
                            }
                        }
                        else{
                            $param['check_admin_ids'] = $flow[0]['flow_uids'];
                        }

                        foreach ($flow as $key => &$value){
                            $value['action_id'] = $id;
                            $value['sort'] = $key;
                            $value['type'] = 4;
                            $value['create_time'] = time();
                        }
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
                    }else{
                        $flow_step = array(
                            'action_id' => $id,
                            'type' => 4,
                            'flow_uids' => $param['check_admin_ids'],
                            'create_time' => time()
                        );
                        //增加审核流程
                        Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);

                    }

                    if ($id){
                      add_log('edit', $id, $this->param,$this->title);
                    }else{
                        add_log('add', $id, $this->param,$this->title);
                    }

                    //发送消息通知
                    $msg=[
                        'from_uid'=>$this->uid,
                        'title'=>'合同审批',
                        'action_id'=>$id
                    ];
                    $users = $param['check_admin_ids'];
                    sendMessage($users,51,$msg);
                }
                $recordId='';
                $recordData=$param;
                if ($id){
                    unset($recordData['id']);
                    $recordData['createId']=$this->uid;
                    $recordData['departId']=$this->did;
                    $recordData['create_time']=time();
                    $recordData['update_time']=time();
                    $recordId=Db::name('sale_contract_record')->strict(false)->field(true)->insertGetId($recordData);

                }
                $recordData=[];
                foreach ($mdId as $key=> $m){
                    $mxData=[
                        'orderId'=>$id,
                        'mdId'=>$mdId[$key]??'',
                        'bjNum'=>$bjNum[$key]??'',
                        'bjPrice'=>$bjPrice[$key]??'',
                        'type'=>$this->scType,
                        'taxMoney'=>$taxMoney[$key]??'',
                        'noTaxPrice'=>$noTaxPrice[$key]??'',
                        'noTaxMoney'=>$noTaxMoney[$key]??'',
                        'bjMoney'=>$bjMoney[$key]??'',
                        'bjTime'=>$bjTime[$key]??'',
                        'remark'=>$remark[$key]??'',
                        'status'=>3,
                        'khlh'=>$khlh[$key]??'',
                        'proCode'=>$proCode[$key]??'',
                        'quotationOderNum'=>$quotationOderNum[$key]??'',
                        'quotationDetailId'=>$quotationDetailId[$key]??0,
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if ($recordId){
                        $recordMx=$mxData;
                        $recordMx['orderId']=$recordId;
                        $recordData[]=$recordMx;
                    }
                    if (isset($mxId[$key])&&$mxId[$key]){
                        unset($mxData['create_time']);
                        $mxData['id']=$mxId[$key];
                    }
                    Db::name('sale_contract_detail')->save($mxData);
                }
                if ($recordData){
                    Db::name('sale_contract_record_detail')->insertAll($recordData);
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        }
        else {
            $countPrice=0;
            $countNum=0;
            $id = isset($param['id']) ? $param['id'] : 0;
            $detail=[];
            $mxList=[];

            $saleUserList=Db::name('admin')
//                ->where('id','in',$detail['saleId'])
                ->where('status',1)
                ->field('id,name')->select();
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                $mxList=Db::name('sale_contract_detail')->alias('qod')
                    ->leftJoin('material_dossier md','md.id=qod.mdId')
                    ->where('qod.status','>',-1)
                    ->where('qod.orderId',$id)
                    ->field('qod.*,md.name as mdName,md.buyCode,md.brand,md.specs,md.unit,md.bar_code')
                    ->select();
                $countNum=Db::name('sale_contract_detail')
                    ->where('status','>',-1)
                    ->where('orderId',$id)->sum('bjNum');
                $countPrice=Db::name('sale_contract_detail')
                    ->where('status','>',-1)
                    ->where('orderId',$id)->sum('bjMoney');

            }else{
                $detail['orderNum']=dJBHBySql($this->table,'orderNum','XS'.date('Ymd'),false,1000);
            }

            $punterList=Db::name('purveyor')->where('status',1)
                ->where('dw_type',2)
                ->field('id,name')->select();
            view::assign('punterList',$punterList);
            $saleUniList=Db::name('department')->where('status',1)->where('pid',0)->field('id,title')->select();
            view::assign('saleUniList',$saleUniList);
            View::assign('mxList', $mxList);
            View::assign('id', $id);
            $is_check_admin = 0;
            $is_create_admin = 0;
            $check_record=[];

            if (!$id){
                $flows = get_cate_department_flows(25,$this->did);
            }else{
                $status=Db::name($this->table)->where('id',$id)->value('status');

                $flows = Db::name('FlowStep')->where(['action_id'=>$detail['id'],'type'=>4,'sort'=>$detail['check_step_sort'],'delete_time'=>0])->find();
                $detail['check_user'] = '-';
                $detail['copy_user'] = '-';
                $check_user_ids = [];
                if ($flows&&$status!=1){
                if($detail['check_status']==1){
                    if($flows['flow_type']==1){
                        $detail['check_user'] = '部门负责人';
                        $check_user_ids[]=get_department_leader($detail['createId']);
                    }
                    else if($flows['flow_type']==2){
                        $detail['check_user'] = '上级部门负责人';
                        $check_user_ids[]=get_department_leader($detail['createId'],1);
                    }
                    else{
                        $check_user_ids = explode(',',$flows['flow_uids']);
                        $check_user = Db::name('Admin')->where('id','in',$flows['flow_uids'])->column('name');
                        $detail['check_user'] = implode(',',$check_user);
                    }
                }
                }else{
                    $flows = get_cate_department_flows(25,$this->did);
                }
                if($detail['copy_uids'] !=''){
                    $copy_user = Db::name('Admin')->where('id','in',$detail['copy_uids'])->column('name');
                    $detail['copy_user'] = implode(',',$copy_user);
                }

                if($detail['createId'] == $this->uid){
                    $is_create_admin = 1;
                }

                $detail['create_user']=Db::name('admin')
                    ->where('id',$detail['createId'])->value('name');
                if(in_array($this->uid,$check_user_ids)){
                    $is_check_admin = 1;
                    //当前审核节点详情
                    $step = Db::name('FlowStep')->where(['action_id'=>$detail['id'],'type'=>4,'sort'=>$detail['check_step_sort'],'delete_time'=>0])->find();
                    if($step['flow_type'] == 4){
                        $check_count = Db::name('FlowRecord')->where(['action_id'=>$detail['id'],'type'=>2,'step_id'=>$step['id'],'check_user_id'=>$this->uid])->count();
                        if($check_count>0){
                            $is_check_admin = 0;
                        }
                    }
                }
                $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
                    ->alias('f')
                    ->join('Admin a', 'a.id = f.check_user_id', 'left')
                    ->where(['f.action_id'=>$detail['id'],'f.type'=>4])
                    ->order('check_time desc')
                    ->select()->toArray();
                foreach ($check_record as $kk => &$vv) {
                    $vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
                    $vv['status_str'] = '提交';
                    if($vv['status'] == 1){
                        $vv['status_str'] = '审核通过';
                    }
                    else if($vv['status'] == 2){
                        $vv['status_str'] = '审核拒绝';
                    }
                    if($vv['status'] == 3){
                        $vv['status_str'] = '撤销';
                    }
                }
            }
            View::assign('is_create_admin', $is_create_admin);
            View::assign('flows', $flows);
            View::assign('detail', $detail);
            View::assign('is_check_admin', $is_check_admin);
            View::assign('check_record', $check_record);
            View::assign('uid', $this->uid);

            View::assign('saleUserList', $saleUserList);

            $projectList=Db::name('project')->where('status','in',[1,2,3])
                ->field('id,name')->select();
            View::assign('projectList', $projectList);
            View::assign('thisDate',date('Y-m-d'));
            $payTypeList=Db::name('quo_order_pay_type')
                ->where('status',1)
                ->field('id,name')->select();
            View::assign('payTypeList',$payTypeList);
            $quoOrderTax=getOrderTax();
            View::assign('quoOrderTax',$quoOrderTax);
            View::assign(['countPrice'=>$countPrice,'countNum'=>$countNum]);
            $tag=$this->module.'/'.$this->controller;
            $pTag=strtolower($tag);
            $printTemplateList=getPrintModelList($pTag);
            View::assign('printTemplateList',$printTemplateList);
            return view('form');
        }
    }

    public function info($id='')
    {
        $detail = Db::name($this->table)->where('id', $id)->find();
        $mxList=Db::name('sale_contract_detail')->alias('qod')
            ->leftJoin('material_dossier md','md.id=qod.mdId')
            ->where('qod.status','>',-1)
            ->where('qod.orderId',$id)
            ->field('qod.*,md.name as mdName,md.buyCode,md.brand,md.specs,md.unit,md.bar_code')
            ->select();
        $countNum=Db::name('sale_contract_detail')
            ->where('status','>',-1)
            ->where('orderId',$id)->sum('bjNum');
        $countPrice=Db::name('sale_contract_detail')
            ->where('status','>',-1)
            ->where('orderId',$id)->sum('bjMoney');
        $projectList=Db::name('project')->where('status','in',[1,2,3])
            ->field('id,name')->select();
        View::assign('projectList', $projectList);
        View::assign('thisDate',date('Y-m-d'));
        $payTypeList=Db::name('quo_order_pay_type')
            ->where('status',1)
            ->field('id,name')->select();
        View::assign('payTypeList',$payTypeList);
        $quoOrderTax=getOrderTax();
        View::assign('quoOrderTax',$quoOrderTax);
        View::assign(['countPrice'=>$countPrice,'countNum'=>$countNum]);
        View::assign('detail', $detail);
        $punterList=Db::name('purveyor')->where('status',1)
            ->where('dw_type',2)
            ->field('id,name')->select();
        view::assign('punterList',$punterList);
        $saleUniList=Db::name('department')->where('status',1)->where('pid',0)->field('id,title')->select();
        view::assign('saleUniList',$saleUniList);
        View::assign('mxList', $mxList);
        $saleUserList=Db::name('admin')
//                ->where('id','in',$detail['saleId'])
            ->where('status',1)
            ->field('id,name')->select();
        view::assign('saleUserList',$saleUserList);
        view::assign('id',$id);
        return view();
}
    public function addMx()
    {
        if (request()->isPost()) {
            $where[]=['status','=',1];
            foreach (['bar_code','name','brand','specs','buyCode'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            $limit=$this->param['limit']??15;
            $list=Db::name('material_dossier')
                ->field("*")
                ->where($where)->paginate($limit);
            return table_assign(0, '', $list);
        } else {
            return view('mx');
        }
    }

    public function edit()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
//            halt($param);
            $mx=$param['mx']??[];
            unset($param['mx']);
            if (!$mx){
                return to_assign(1,'请添加明细');
            }
            if (!$param['punterId']||!$param['salesUnitId']
                ||!$param['saleId']){
                return to_assign(1,'参数有误');
            }
            $mxId=$mx['mxid']??[];
            $mdId=$mx['mdId']??[];
            $bjNum=$mx['bjNum']??[];
            $bjPrice=$mx['bjPrice']??[];
//            $mdPrice=$mx['mdPrice']??[];
            $discount=$mx['discount']??[];
            $taxMoney=$mx['taxMoney']??[];
            $noTaxPrice=$mx['noTaxPrice']??[];
            $noTaxMoney=$mx['noTaxMoney']??[];
            $bjMoney=$mx['bjMoney']??[];
            $bjTime=$mx['bjTime']??[];
            $remark=$mx['remark']??[];
            $khlh=$mx['khlh']??[];
            $proCode=$mx['proCode']??[];
            $quotationOderNum=$mx['quotationOderNum']??[];
            $quotationDetailId=$mx['quotationDetailId']??[];
//            $timeLong=$mx['timeLong']??[];
            $param['update_time']=time();
            $countMoney=0;
            foreach ($bjMoney as $v){
                $countMoney+=$v;
            }
            $param['countMoney']=$countMoney;
            $id=$this->param['id']??0;

            Db::startTrans();
            try {
                if ($id > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $param,$this->title);

                }
                $recordId='';
                $recordData=$param;
                unset($recordData['id']);
                $recordData['createId']=$this->uid;
                $recordData['departId']=$this->did;
                $recordData['create_time']=time();
                $recordData['update_time']=time();
                $recordId=Db::name('sale_contract_record')->strict(false)->field(true)->insertGetId($recordData);

                $recordData=[];
                foreach ($mdId as $key=> $m){
                    $mxData=[
                        'orderId'=>$id,
                        'mdId'=>$mdId[$key]??'',
                        'bjNum'=>$bjNum[$key]??'',
                        'bjPrice'=>$bjPrice[$key]??'',
                        'type'=>$this->scType,
                        'taxMoney'=>$taxMoney[$key]??'',
                        'noTaxPrice'=>$noTaxPrice[$key]??'',
                        'noTaxMoney'=>$noTaxMoney[$key]??'',
                        'bjMoney'=>$bjMoney[$key]??'',
                        'bjTime'=>$bjTime[$key]??'',
                        'remark'=>$remark[$key]??'',
                        'khlh'=>$khlh[$key]??'',
                        'proCode'=>$proCode[$key]??'',
                        'quotationOderNum'=>$quotationOderNum[$key]??'',
                        'quotationDetailId'=>$quotationDetailId[$key]??0,
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if ($recordId){
                        $recordMx=$mxData;
                        $recordMx['orderId']=$recordId;
                        $recordData[]=$recordMx;
                    }
                    if (isset($mxId[$key])&&$mxId[$key]){
                        unset($mxData['create_time']);
                        $mxData['id']=$mxId[$key];
                    }
                    Db::name('sale_contract_detail')->save($mxData);
                }
                if ($recordData){
                    Db::name('sale_contract_record_detail')->insertAll($recordData);
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        }
        else {
            $countPrice=0;
            $countNum=0;
            $id = isset($param['id']) ? $param['id'] : 0;
            $detail=[];
            $mxList=[];

            $saleUserList=Db::name('admin')
//                ->where('id','in',$detail['saleId'])
                ->where('status',1)
                ->field('id,name')->select();
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                $mxList=Db::name('sale_contract_detail')->alias('qod')
                    ->leftJoin('material_dossier md','md.id=qod.mdId')
                    ->where('qod.status','>',-1)
                    ->where('qod.orderId',$id)
                    ->field('qod.*,md.name as mdName,md.buyCode,md.brand,md.specs,md.unit,md.bar_code')
                    ->select();
                $countNum=Db::name('sale_contract_detail')
                    ->where('status','>',-1)
                    ->where('orderId',$id)->sum('bjNum');
                $countPrice=Db::name('sale_contract_detail')
                    ->where('status','>',-1)
                    ->where('orderId',$id)->sum('bjMoney');

            }else{
                $detail['orderNum']=dJBHBySql($this->table,'orderNum','XS'.date('Ymd'),false,1000);
            }

            $punterList=Db::name('purveyor')->where('status',1)
                ->where('dw_type',2)
                ->field('id,name')->select();
            view::assign('punterList',$punterList);
            $saleUniList=Db::name('department')->where('status',1)->where('pid',0)->field('id,title')->select();
            view::assign('saleUniList',$saleUniList);
            View::assign('mxList', $mxList);
            View::assign('id', $id);


            View::assign('detail', $detail);


            View::assign('saleUserList', $saleUserList);

            $projectList=Db::name('project')->where('status','in',[1,2,3])
                ->field('id,name')->select();
            View::assign('projectList', $projectList);
            View::assign('thisDate',date('Y-m-d'));
            $payTypeList=Db::name('quo_order_pay_type')
                ->where('status',1)
                ->field('id,name')->select();
            View::assign('payTypeList',$payTypeList);
            $quoOrderTax=getOrderTax();
            View::assign('quoOrderTax',$quoOrderTax);
            View::assign(['countPrice'=>$countPrice,'countNum'=>$countNum]);
            $tag=$this->module.'/'.$this->controller;
            $pTag=strtolower($tag);
            $printTemplateList=getPrintModelList($pTag);
            View::assign('printTemplateList',$printTemplateList);
            return view('');
        }
    }
    /***
     * @autho:xiangzi
     * @auth:true
     * @Date:2024/12/6
     * 关联报价单
     */
    public function quoOrder()
    {
        $khId=$this->param['khId']??'';
        $detailIds=$this->param['detailIds']??'';
        if ($this->request->isPost()){
            if (!$khId){
                return table_assign(1, '请选择客户');
            }
            $where[]=['qod.status','=',2];
            $where[]=['qo.punterId','=',$khId];
            if ($detailIds){
                $where[]=['qod.id','not in',explode(',',$detailIds)];
            }
            foreach (['bar_code','name','brand','specs','buyCode'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            if (isset($this->param['orderNum'])&&$this->param['orderNum']){
                $where[]=['qo.orderNum','like','%'.$this->param['orderNum'].'%'];
            }
            $limit=$this->param['limit']??15;
            $list=Db::name('quotation_order_detail')
                ->alias('qod')
                ->leftJoin('quotation_order qo','qo.id=qod.orderId')
                ->leftJoin('material_dossier md','md.id=qod.mdID')
                ->field("qod.id as quotationDetailId,qo.orderNum as quotationOderNum,md.name,
                md.id,md.bar_code,md.brand,md.specs,md.unit,md.buyCode,md.proPrice,
                qod.bjNum,qod.bjPrice,qod.noTaxPrice,qod.bjMoney")
                ->where($where)->paginate($limit);
            return table_assign(0, '', $list);
        }else{
            view::assign('khId',$khId);
            view::assign('detailIds',$detailIds);
            return view('bj_mx');
        }
}
    public function removeMx()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        Db::startTrans();
        try {
            Db::name('sale_contract_detail')
                ->where('id',$ids)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title.'明细');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }

    public function delete()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            Db::name('sale_contract_detail')
                ->where('status','>',-1)
                ->where('orderId','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }

    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id',$id)->value('status');
        if ($status!=1){
            return to_assign(1,'参数有误');
        }
        $mx=Db::name('sale_contract_detail')->where('status',1)->where('orderId',$id)->count();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }

        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'sureId'=>$this->uid,
                'sureTime'=>time(),
                'status'=>2,
                'update_time'=>time()]);
            Db::name('sale_contract_detail')->where('status',1)
                ->where('orderId',$id)->update(['status'=>2,'update_time'=>time()]);
            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }  
    public function onSub()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id',$id)->value('status');
        if ($status!=2){
            return to_assign(1,'参数有误');
        }
        $mx=Db::name('sale_contract_detail')->where('status',2)->where('orderId',$id)->count();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }

        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'status'=>3,
                'update_time'=>time()]);
            Db::name('sale_contract_detail')->where('status',2)
                ->where('orderId',$id)->update(['status'=>3,'update_time'=>time()]);
            add_log('apply', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }

    public function onChick()
    {
        $id=$this->param['id']??0;
        $type=$this->param['types']??1;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id',$id)->value('status');
        if ($status!=3){
            return to_assign(1,'参数有误');
        }
        $mx=Db::name('sale_contract_detail')->where('status',3)->where('orderId',$id)->count();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }
        $status1=$type==1?4:5;
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>time(),
                'status'=>$status1,
                'update_time'=>time()]);
            add_log('check', $id, $this->param,$this->title);
            Db::name('sale_contract_detail')->where('status',3)
                ->where('orderId',$id)->update(['status'=>$status1,'update_time'=>time()]);
            Db::commit();
            add_log($type==1?'check':'refue', $id, $this->param,$this->title);
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
    
    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                $punterId=[];
                $salesUnitId=[];
                $saleId=[];
                $tax=[];
                $contactId=[];
                $saveId=[];
                $orderDate=[];
                $mdId=[];
                $bjNum=[];
                $bjPrice=[];
                $proCode=[];
                $bjTime=[];
                $remark=[];
                $quotationOderNum=[];
                $quotationDetailId=[];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {
                    $punterId[]=(int)$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    if ($punterId){
                        $salesUnitId[]=(int)$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                        $saleId[]=(int)$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                        $tax[]=(float)$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                        $contactId[]=(int)$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
                        $saveId[]=(int)$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                        $orderDate[]=(string)$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getFormattedValue();
                        $mdId[]=(int)$objPHPExcel->getActiveSheet()->getCell("H" . $j)->getFormattedValue();
                        $bjNum[]=(float)$objPHPExcel->getActiveSheet()->getCell("I" . $j)->getFormattedValue();
                        $bjPrice[]=(float)$objPHPExcel->getActiveSheet()->getCell("J" . $j)->getFormattedValue();
                        $bjTime[]=$objPHPExcel->getActiveSheet()->getCell("K" . $j)->getFormattedValue();
                        $proCode[]=$objPHPExcel->getActiveSheet()->getCell("L" . $j)->getFormattedValue();
                        $quotationOderNum[]=$objPHPExcel->getActiveSheet()->getCell("M" . $j)->getFormattedValue();
                        $quotationDetailId[]=(int)$objPHPExcel->getActiveSheet()->getCell("N" . $j)->getFormattedValue();
                        $remark[]=$objPHPExcel->getActiveSheet()->getCell("O" . $j)->getFormattedValue();
                    }
                }
                $res=$this->createImportData($punterId,$salesUnitId,$saleId,$tax,
                    $contactId,$saveId,$orderDate,$mdId,$bjNum,$bjPrice,$bjTime,$proCode,$quotationOderNum,$quotationDetailId,$remark);
                if ($res['code']!=0){
                    throw new Exception($res['msg']);
                }
                $zhuData=$res['data']['orderData'];
                $mxData=$res['data']['mxData'];
                if ($zhuData){
                    $id= Db::name($this->table)->insertGetId($zhuData);
                    foreach ($mxData as &$v){
                        $v['orderId']=$id;
                    }
                    Db::name('sale_contract_detail')->insertAll($mxData);
                    add_log('import', $id,$res['data'] ,$this->title);
                }
                Db::commit();
            }

        }catch (Exception $e){
            Db::rollback();
            add_log('import', '', $e->getMessage(),$this->title);
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }

    public function createImportData($punterId,$salesUnitId,$saleId,$tax,
                                     $contactId,$saveId,$orderDate,$mdId,$bjNum,$bjPrice,$bjTime,
                                     $proCode,$quotationOderNum,$quotationDetailId,$remark)
    {
        $punterId=array_unique($punterId);
        $salesUnitId=array_unique($salesUnitId);
        $saleId=array_unique($saleId);
        $tax=array_unique($tax);
        $contactId=array_unique($contactId);
        $saveId=array_unique($saveId);
        $orderDate=array_unique($orderDate);
        if (count($punterId)!=1||count($salesUnitId)!=1||count($saleId)!=1||count($tax)!=1
            ||count($contactId)!=1||count($saveId)!=1||count($orderDate)!=1){
            return ['code'=>1,'msg'=>'参数不一致'];
        }
        $punterId1=Db::name('purveyor')->where('status',1)->where('id',$punterId[0])->value('id');
        $salesUnitId1=Db::name('department')->where('status',1)->where('id',$salesUnitId[0])->value('id');
        $saleId1=Db::name('admin')->where('did',$salesUnitId1)->where('status',1)->where('id',$saleId[0])->value('id');
        $contactId1=Db::name('purveyor_member')->where('purveyorId',$punterId1)
            ->where('status',1)->where('type',1)->where('id',$contactId[0])->find();
        $saveId1=Db::name('purveyor_member')->where('purveyorId',$punterId1)
            ->where('status',1)->where('type',2)->where('id',$saveId[0])->find();
        if (!$punterId1||!$salesUnitId1||!$saleId1||!$contactId1||!$saveId1){
            return  ['code'=>1,'msg'=>'参数有误'];
        }
        $zuData=[
            'orderNum'=>dJBHBySql($this->table,'orderNum','XS'.date('Ymd'),false,1000),
            'punterId'=>$punterId1,
            'salesUnitId'=>$salesUnitId1,
            'saleId'=>$saleId1,
            'contactId'=>$contactId1['id'],
            'contactName'=>trim($contactId1['name']),
            'contactPhone'=>trim($contactId1['phone']),
            'saveId'=>$saveId1['id'],
            'saveName'=>$saveId1['name'],
            'savePhone'=>$saveId1['phone'],
            'saveAdd'=>$saveId1['address'],
            'orderDate'=>trim($orderDate[0]),
            'tax'=>$tax[0],
            'type'=>$this->scType,
            'createId'=>$this->uid,
            'departId'=>$this->did,
            'create_time'=>time(),
            'update_time'=>time()
        ];

        $countMoney=0;
        $mxData=[];
        $tax1=$tax[0]/100;
        foreach ($mdId as $k=>$v){
            if (empty($mdId[$k])||empty($bjNum[$k])||empty($proCode[$k])||empty($bjTime[$k])){
                return ['code'=>1,'msg'=>$k+1 .'行参数不能为空'];
            }
            $mdInfo=Db::name('material_dossier')->where('status',1)->where('id',$v)->find();
            if (!$mdInfo){
                return ['code'=>1,'msg'=>$k+1 .'行物料不存在'];
            }
            if ($quotationOderNum[$k]){
                $quotationOderInfo=Db::name('quotation_order_detail')
                    ->alias('qod')
                    ->leftJoin('quotation_order qo','qo.id=qod.orderId')
                    ->where('qo.status',2)
                    ->where('qo.orderNum',trim($quotationOderNum[$k]))
                    ->where('qod.id',$quotationDetailId[$k])
                    ->where('qod.status',2)->find()??[];
                if (!$quotationOderInfo){
                    return ['code'=>1,'msg'=>$k+1 .'行关联单据有误'];
                }

            }
            $bjNum1=$bjNum[$k];
            $bjPrice1=$bjPrice[$k];
            $noTaxPrice=round((($bjPrice1)/(1-$tax1)),2);
            $bjMoney=round(($bjPrice1*$bjNum1),2);
            $noTaxMoney=round($bjNum1*$noTaxPrice,2);
            $taxMoney=abs(round($bjMoney-$noTaxMoney,2));
            $countMoney+=$bjMoney;
            $mxData[]=[
                'mdId'=>$mdId[$k],
                'bjNum'=>$bjNum[$k],
                'bjPrice'=>$bjPrice[$k],
                'quotationDetailId'=>$quotationDetailId[$k]??0,
                'quotationOderNum'=>$quotationOderNum[$k]??'',
                'taxMoney'=>$taxMoney,
                'noTaxMoney'=>$noTaxMoney,
                'noTaxPrice'=>$noTaxPrice,
                'bjMoney'=>$bjMoney,
                'type'=>$this->scType,
                'bjTime'=>trim($bjTime[$k]),
                'remark'=>trim($remark[$k])??'',
                'proCode'=>trim($proCode[$k])??'',
                'create_time'=>time(),
                'update_time'=>time(),
            ];
        }
        $zuData['countMoney']=$countMoney;
        return ['code'=>0,'msg'=>'操作成功','data'=>['orderData'=>$zuData,'mxData'=>$mxData]];
    }

    public function onCancel()
    {
       $id=$this->param['id']??'';
       if (!$id){
           return to_assign(1,'操作有误');
       }

        try {
            $checkData=array(
                'action_id' => $id,
                'check_user_id' => $this->uid,
                'content' => '撤回申请',
                'type' => 4,
                'status' => 3,
                'check_time' => time(),
                'create_time' => time()
            );
            Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);

            Db::name($this->table)->where('id',$id)->update(['status'=>1]);
//           Db::name('FlowStep')->where('delete_time',0)->where('action_id',$id)->update(['delete_time'=>time()]);
        }catch (\Exception $e){
           return  to_assign(1,'操作失败:'.$e->getMessage());
        }

       return to_assign();
}

    public function printPage($id)
    {
        $id=$this->param['id']??'';
        $info=Db::name($this->table)->where('sc.id',$id)
            ->alias('sc')
            ->leftJoin('purveyor p','p.id=sc.punterId')
            ->leftJoin('department d','d.id=sc.salesUnitId')
            ->leftJoin('quo_order_pay_type qodpt','qodpt.id=sc.payType')
            ->field("sc.*,p.name as pName,d.title as saleUnit,qodpt.name as payTypeName")
            ->find();
        $saleUserList=Db::name('admin')
                ->where('id','in',$info['saleId'])
            ->where('status',1)
            ->field('id,name')->column('name');
        $mxList=Db::name('sale_contract_detail')->alias('qod')
            ->leftJoin('material_dossier md','md.id=qod.mdId')
            ->where('qod.status','>',-1)
            ->where('qod.orderId',$id)
            ->field('qod.*,md.name as mdName,md.buyCode,md.brand,md.specs,md.unit,md.bar_code')
            ->select();
        $tempMode=Db::name('print_template')
            ->where('id',$info['printTemplate'])
            ->where('status',1)->order('update_time DESC')
            ->limit(1)
            ->find();
        $data=[
//            'printName'=>'合同打印',
            'printName'=>$tempMode['name'],
            'orderNum'=>$info['orderNum'],
            'type'=>$info['type'],
            'pName'=>$info['pName'],
            'orderDate'=>$info['orderDate'],
            'saleUnit'=>$info['saleUnit'],
            'taxStr'=>$info['tax'],
            'payTypeName'=>$info['payTypeName'],
            'saleUser'=>implode(',',$saleUserList),
            'contactName'=>$info['contactName'],
            'contactPhone'=>$info['contactPhone'],
            'saveName'=>$info['saveName'],
            'savePhone'=>$info['savePhone'],
        ];
        $detail=[];
        foreach ($mxList as $k=> $ml){
            $detail[]=[
                'k'=>$k+1,
                'brand'=>$ml['brand'],
                'mdName'=>$ml['mdName'],
                'buyCode'=>$ml['buyCode'],
                'specs'=>$ml['specs'],
                'unit'=>$ml['unit'],
                'bjNum'=>$ml['bjNum'],
                'noTaxPrice'=>$ml['noTaxPrice'],
                'bjPrice'=>$ml['bjPrice'],
                'bjMoney'=>$ml['bjMoney'],
                'noTaxMoney'=>$ml['noTaxMoney'],
                'taxMoney'=>$ml['taxMoney'],
                'bjTime'=>$ml['bjTime'],
                'khlh'=>$ml['khlh'],
                'proCode'=>$ml['proCode'],
                'remark'=>$ml['remark'],
            ];
        }

        $res=[];
        foreach ($detail as $key=>$v){
            $res[$key]=$v;
        }
        $data['detail']=$res;

        $temp=$tempMode['tplBody']??'';
        View::assign('temp',$temp);
        View::assign('info',json_encode($data,320));
        return view('../../base/view/common/print_page');
}
}